package com.os.config;

import com.os.data.DataHashCache;
import com.os.constant.Sys;
import com.os.task.Heartbeat;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.net.InetAddress;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 风亦未止
 * @date 2023/5/2 15:30
 */
@Data
@Configuration
@Slf4j
public class ConfigInit {
    @Value("${server.port}")
    private String port;
    @Value("${server.os.path}")
    private String path;

    public String queueName;

    public String dataPath;

    public String tempRootPath;

    public String host;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private InetAddress inetAddress;

    @Autowired
    private MessagePostProcessor messagePostProcessor;


    @PostConstruct
    private void init() {
        if (StringUtils.isEmpty(path)) {
            log.error("存储路径为空,请先配置！oss.path : null");
            throw new RuntimeException("存储路径为空,请先配置！");
        }
        this.dataPath = path + Sys.SEPARATOR + "data-" + port;
        this.tempRootPath = dataPath + Sys.SEPARATOR + "temp";
        this.queueName = "data_queue" + port;
        File file = new File(dataPath);
        if (!file.exists()) {
            boolean mkdir = file.mkdirs();
            if (!mkdir) {
                throw new RuntimeException(String.format("初始化存储路径失败,请检查路径是否合法:%s", dataPath));
            }
            File tempFile = new File(tempRootPath);
            tempFile.mkdirs();
            log.info(String.format("构建路径：%s", dataPath));
            log.info(String.format("临时文件路径：%s", tempRootPath));
        } else {
            //扫盘数据信息放入缓存 hash.index.data
            collectObj(file);
        }
        this.host = inetAddress.getHostAddress() + ":" + port;
        Heartbeat heartbeat = new Heartbeat(rabbitTemplate, messagePostProcessor, host);
        threadPoolExecutor.submit(heartbeat);
    }

    /**
     * 该目录下尽量只有文件 hash.index.data
     *
     * @param file
     */
    public void collectObj(File file) {
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                String[] f = files[i].getName().split("\\.");
                String hash = f[0];
                int index = Integer.parseInt(f[1]);
                DataHashCache.dataHashCache.put(hash, index);
            }
        }
    }

}
